#include "drv_tmos.h"
#include "public_apis.h"

#define TAG "TMOS"

__attribute__((aligned(4))) uint32_t MEM_BUF[BLE_MEMHEAP_SIZE / 4];

static public_task_cb_t drv_task_cb[15] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
static void *drv_task_arg[15] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
static tmosTaskID dev_task_id;

static void drv_tmos_task_start(public_task_cb_t cb, void *arg, uint32_t period)
{

    for (size_t i = 0; i < 15; i++)
    {
        if (drv_task_cb[i] == NULL)
        {
            drv_task_cb[i] = cb;
            drv_task_arg[i] = arg;
            if (period)
                tmos_start_task(dev_task_id, 1 << i, MS1_TO_SYSTEM_TIME(period));
            else
                tmos_set_event(dev_task_id, 1 << i);
            return;
        }
    }
}

static tmosEvents drv_task_event(tmosTaskID task_id, tmosEvents events)
{
    for (size_t i = 0; i < 15; i++)
    {
        if ((events & (1 << i)))
        {
            drv_task_cb[i](drv_task_arg[i]);
            drv_task_cb[i] = NULL;
            return events ^ (1 << i);
        }
    }
}

void drv_tmos_install()
{
    CH58X_BLEInit();        // 蓝牙初始化
    HAL_Init();             // 蓝牙抽象层初始化
    GAPRole_ObserverInit(); // 观察者模式初始化

    dev_task_id = TMOS_ProcessEventRegister(drv_task_event);
    public_task_register_cb(drv_tmos_task_start);
}
